package com.leve.admin.service.impl;

import com.leve.admin.common.ResultUtil;
import com.leve.admin.common.XiaomiPush;
import com.leve.admin.domain.*;
import com.leve.admin.repository.GhostRepository;
import com.leve.admin.repository.MonmentRepository;
import com.leve.admin.repository.UserRepository;
import com.leve.admin.service.GhostService;
import com.leve.admin.service.PushService;
import com.leve.admin.service.ReceiverService;
import com.xiaomi.xmpush.server.Result;
import lombok.extern.slf4j.Slf4j;
import org.json.simple.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class GhostServiceImpl implements GhostService {
    @Autowired
    private ReceiverService receiverService;
    @Autowired
    private GhostRepository ghostRepository;
    @Autowired
    private PushService pushService;
    @Autowired
    private UserRepository userRepository;
    @Autowired
    private MonmentRepository monmentRepository;
    @Value("${yunxin.team_im_id}")
    private String team_im_id;

    @Override
    public List<Ghost> ghosts(PageRequest pageRequest, String name, String statusId) {
        //    1.用户列表信息呈现：头像、性别、手机号码、UPC数量、此刻数量、未查看聊天消息数量、加入的话题、最后登录时间、注册时间、地域
        List<Ghost> ghosts = ghostRepository.ghosts(pageRequest, name, statusId);
        ghosts.forEach(ghost -> {
            User user = userRepository.selectByid(ghost.getUser_id());
            ghost.setPhone(user.getPhone());
            //upc 数量
            Map map = userRepository.monthIncome(ghost.getEos_account().getAddress());
            if (map != null) {
                ghost.setUpc(new Double(map.get("totalAmount").toString()));
            }
            //好友数
            ghost.setFriendsNumber(ghostRepository.findGhostFriends(ghost.getId()).size());
            //up数
            ghost.setUpNumber(ghostRepository.findGreetings((ghost.getId())).size());

        });
        return ghosts;
    }

    @Override
    public ResultBase getservers() {
        return ResultUtil.success(0, "客服列表", null, ghostRepository.getservers());
    }

    @Override
    public ResultBase sendMsg(List<String> ids, String text, String flag) {
        if ("true".equals(flag)) {
            //TODO 系统推送

        } else {
            //TODO IM消息推送
            for (String gid : ids) {
                Ghost ghost = ghostRepository.selectOneByGost(gid);
                receiverService.sendMessage(team_im_id, ghost.getIm_id(), text);
            }
        }
        return ResultUtil.success(0, "IM消息推送中", null, null);
    }

    @Override
    public ResultBase smsMsg(List<String> ids, String text) {
        for (String gid : ids) {
            User user = userRepository.selectByGid(gid);
            //大汉三通短信发送接口
            String phone = user.getPhone();
        }
        return null;
    }

    @Override
    public ResultBase createGhostGroup(String checkList, String text) {
        GroupType groupType = new GroupType();
        groupType.setName(text);
        //TODO 自定义用户组
        groupType.setStatus(1);
        userRepository.createGroupType(groupType);
        return ResultUtil.success(0, "创建用户组", null, null);

    }

    @Override
    public ResultBase getGhostGroups(String flag) {
        List<GroupType> groupTypes;
        if (flag == null) {
            groupTypes = userRepository.getGroupTypes();
        } else {
            groupTypes = userRepository.getGroupTypes(Integer.parseInt(flag));
            for (GroupType groupType : groupTypes) {
                List<UserGroup> userGroupBygroup = userRepository.findUserGroupBygroupTypeId(groupType.getId());
                List<Ghost> ghosts = new ArrayList<>();
                for (UserGroup userGroup : userGroupBygroup) {
                    ghosts.add(userGroup.getGhost());
                }
                groupType.setGhosts(ghosts);
            }

        }
        return ResultUtil.success(0, "分组信息", null, groupTypes);
    }

    @Override
    public ResultBase distribution(List<String> ids, String statusId) {

        GroupType groupType = userRepository.OneGroupType(statusId);
        int userTotal = groupType.getUserTotal();
        List<UserGroup> userGroups = new ArrayList<>();
        UserGroup userGroup;
        for (String gid : ids) {
            if (gid != null) {
                userGroup = new UserGroup();
                userGroup.setGid(gid);
                userGroup.setGhost(ghostRepository.selectOneByGost(gid));
                userGroup.setGroupType(groupType);
                userGroups.add(userGroup);
            }

        }
        groupType.setUserTotal(userGroups.size() + userTotal);
        userRepository.updateUserTotal(groupType);
        userRepository.distribution(userGroups);
        return ResultUtil.success(0, "用户分配", null, userGroups);
    }

    @Override
    public ResultBase delGroup(String statusId) {
        GroupType groupType = userRepository.OneGroupType(statusId);
        int userTotal = groupType.getUserTotal();
        if (userTotal > 0) {
            return ResultUtil.success(-1, "当前分组用户大于0", null, null);
        }
        userRepository.delGroup(statusId);
        return ResultUtil.success(0, "删除成功", null, null);
    }

    /**
     * 根据指定时间范围查询注册用户
     */
    @Override
    public ResultBase findGhostByCreateDate() {

        List<GroupType> lsits = new ArrayList<>();
        GroupType groupType1 = new GroupType();
        groupType1.setId("1_create");
        groupType1.setName("今日注册");
        Map ghostCountByCreateDate = ghostRepository.findGhostCountByCreateDate(0, null);
        setTotalCount(groupType1, ghostCountByCreateDate);
        groupType1.setUserTotal(1);
        lsits.add(groupType1);

        GroupType groupType2 = new GroupType();
        groupType2.setId("1_login");
        groupType2.setName("今日登陆");
        Map ghostCountBylastDate = ghostRepository.findGhostCountBylastDate(0, null);
        setTotalCount(groupType2, ghostCountBylastDate);
        lsits.add(groupType2);

        GroupType groupType3 = new GroupType();
        groupType3.setId("7_login");
        groupType3.setName("7天内登陆");
        Map ghostCountBylastDate1 = ghostRepository.findGhostCountBylastDate(7, null);
        setTotalCount(groupType3, ghostCountBylastDate1);
        lsits.add(groupType3);

        GroupType groupType4 = new GroupType();
        groupType4.setId("7_create");
        groupType4.setName("7天内注册");
        Map ghostCountBylastDate4 = ghostRepository.findGhostCountByCreateDate(7, null);
        setTotalCount(groupType4, ghostCountBylastDate4);
        lsits.add(groupType4);


        GroupType groupType5 = new GroupType();
        groupType5.setId("7_create_MALE");
        groupType5.setName("7天内注册男性");
        Map ghostCountBylastDate5 = ghostRepository.findGhostCountByCreateDate(7, "MALE");
        setTotalCount(groupType5, ghostCountBylastDate5);
        lsits.add(groupType5);

        GroupType groupType6 = new GroupType();
        groupType6.setId("7_create_FEMALE");
        groupType6.setName("7天内注册女性");
        Map ghostCountBylastDate6 = ghostRepository.findGhostCountByCreateDate(7, "FEMALE");
        setTotalCount(groupType6, ghostCountBylastDate6);
        lsits.add(groupType6);

        GroupType groupType7 = new GroupType();
        groupType7.setId("31_login");
        groupType7.setName("1月内登陆");
        Map ghostCountBylastDate7 = ghostRepository.findGhostCountBylastDate(31, null);
        setTotalCount(groupType7, ghostCountBylastDate7);
        lsits.add(groupType7);

        GroupType groupType8 = new GroupType();
        groupType8.setId("31_login_MALE");
        groupType8.setName("1月内登陆男性");
        Map ghostCountBylastDate8 = ghostRepository.findGhostCountBylastDate(31, "MALE");
        setTotalCount(groupType8, ghostCountBylastDate8);
        lsits.add(groupType8);

        GroupType groupType9 = new GroupType();
        groupType9.setId("31_login_FEMALE");
        groupType9.setName("1月内登陆女性");
        Map ghostCountBylastDate9 = ghostRepository.findGhostCountBylastDate(31, "FEMALE");
        setTotalCount(groupType9, ghostCountBylastDate9);
        lsits.add(groupType9);
        return ResultUtil.success(0, "常态用户组", null, lsits);
    }

    @Override
    public ResultBase normal() {
        return findGhostByCreateDate();
    }

    @Override
    public ResultBase userPush(List<String> ids, String pushType, String connet) {
        String id = ids.get(0);
        //TODO 分区 自定义分组 常态用户组
        if (id != null && id.length() == 24) {
            List<UserGroup> userGroups = userRepository.findUserGroupBygroupTypeId(id);
            if (userGroups.size() > 0) {
                //自定义分组
                custom(ids, pushType, connet);

            } else {
                //小鬼id全选
                pushByGid(ids, pushType, connet);
            }

        } else {
            normal(ids, pushType, connet);
        }

        return ResultUtil.success(0, "发送中", null, null);
    }

    @Override
    public ResultBase createpost(String imgUrl, String keyValue, String gid) {

        return null;
    }

    @Override
    public ResultBase normalGhosts(String name, PageRequest pageRequest) {
        List<Ghost> ghosts = new ArrayList<>();
        try {
            switch (name) {
                case "1_create":
                    ghosts = ghostRepository.findGhostByCreateDate(0, null, pageRequest);
                    break;
                case "1_login":
                    ghosts = ghostRepository.findGhostBylastDate(0, null, pageRequest);
                    break;
                case "7_login":
                    ghosts = ghostRepository.findGhostBylastDate(7, null, pageRequest);
                    break;
                case "7_create":
                    ghosts = ghostRepository.findGhostByCreateDate(7, null, pageRequest);
                    break;
                case "7_create_MALE":
                    ghosts = ghostRepository.findGhostByCreateDate(7, "MALE", pageRequest);
                    break;
                case "7_create_FEMALE":
                    ghosts = ghostRepository.findGhostByCreateDate(7, "FEMALE", pageRequest);
                    break;
                case "31_login":
                    ghosts = ghostRepository.findGhostBylastDate(31, null, pageRequest);
                    break;
                case "31_login_MALE":
                    ghosts = ghostRepository.findGhostByCreateDate(31, "MALE", pageRequest);
                    break;
                case "31_login_FEMALE":
                    ghosts = ghostRepository.findGhostByCreateDate(31, "FEMALE", pageRequest);
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
        return ResultUtil.success(0, "小鬼详情", null, ghosts);
    }


    public void custom(List<String> ids, String pushType, String connet) {
        for (String id : ids) {
            if (id != null && id.length() == 24) {
                List<UserGroup> userGroups = userRepository.findUserGroupBygroupTypeId(id);

                if (("im").equals(pushType)) {
                    // JSONArray to = new JSONArray();
                    for (UserGroup userGroup : userGroups) {
                        //      to.add(userGroup.getGhost().getIm_id());
                    }
                    //   receiverService.sendBatchMsg(team_im_id, to, connet);
                } else if (("sms").equals(pushType)) {
                    try {
                        StringBuilder phones = new StringBuilder();
                        for (UserGroup userGroup : userGroups) {
                            User user = userRepository.selectByGid(userGroup.getGid());
                            phones.append(user.getPhone()).append(",");
                        }
                        pushService.sendSms(phones.toString(), "", connet);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else if (("sys").equals(pushType)) {
                    try {
                        List<String> param = new ArrayList<>();
                        for (UserGroup userGroup : userGroups) {
                            param.add(userGroup.getGid());
                        }
                        Result result = XiaomiPush.sendMessageToAliases(ids, "乐无通知", "乐无通知", connet);
                        log.info("Server response: ", "MessageId: " + result.getMessageId()
                                + " ErrorCode: " + result.getErrorCode().toString()
                                + " Reason: " + result.getReason());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }


            }
        }

    }

    public void pushByGid(List<String> ids, String pushType, String connet) {


        if (("im").equals(pushType)) {
            try {
                JSONArray to = new JSONArray();
                for (String id : ids) {
                    Ghost ghost = ghostRepository.selectOneByGost(id);
                    to.add(ghost.getIm_id());
                }
                receiverService.sendBatchMsg(team_im_id, to, connet);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (("sms").equals(pushType)) {
            try {
                StringBuilder phones = new StringBuilder();
                for (String id : ids) {
                    User user = userRepository.selectByGid(id);
                    phones.append(user.getPhone()).append(",");
                }
                pushService.sendSms(phones.toString(), "", connet);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (("sys").equals(pushType)) {
            try {
                Result result = XiaomiPush.sendMessageToAliases(ids, "乐无通知", "乐无通知", connet);
                log.info("Server response: ", "MessageId: " + result.getMessageId()
                        + " ErrorCode: " + result.getErrorCode().toString()
                        + " Reason: " + result.getReason());
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


    }

    public void normal(List<String> ids, String pushType, String connet) {
        List<Ghost> ghosts = new ArrayList<>();
        for (String id_name : ids) {
            if (id_name == null) {
                continue;
            }
            try {
                switch (id_name) {
                    case "1_create":
                        ghosts = ghostRepository.findGhostByCreateDate(0, null);
                        pushMsg(ghosts, pushType, connet);
                        break;
                    case "1_login":
                        ghosts = ghostRepository.findGhostBylastDate(0, null);
                        pushMsg(ghosts, pushType, connet);
                        break;
                    case "7_login":
                        ghosts = ghostRepository.findGhostBylastDate(7, null);
                        pushMsg(ghosts, pushType, connet);

                        break;
                    case "7_create":
                        ghosts = ghostRepository.findGhostByCreateDate(7, null);
                        pushMsg(ghosts, pushType, connet);
                        break;
                    case "7_create_MALE":
                        ghosts = ghostRepository.findGhostByCreateDate(7, "MALE");
                        pushMsg(ghosts, pushType, connet);
                        break;
                    case "7_create_FEMALE":
                        ghosts = ghostRepository.findGhostByCreateDate(7, "FEMALE");
                        pushMsg(ghosts, pushType, connet);
                        break;
                    case "31_login":
                        ghosts = ghostRepository.findGhostBylastDate(31, null);
                        pushMsg(ghosts, pushType, connet);
                        break;
                    case "31_login_MALE":
                        ghosts = ghostRepository.findGhostByCreateDate(31, "MALE");
                        pushMsg(ghosts, pushType, connet);
                        break;
                    case "31_login_FEMALE":
                        ghosts = ghostRepository.findGhostByCreateDate(31, "FEMALE");
                        pushMsg(ghosts, pushType, connet);
                }
            } catch (Exception e) {
                log.info(e.getMessage());
            }
            ghosts.clear();
        }

    }

    private void pushMsg(List<Ghost> ghosts, String pushType, String connet) throws Exception {

        if (("im").equals(pushType)) {
            JSONArray to = new JSONArray();
            for (Ghost ghost : ghosts) {
                to.add(ghost.getIm_id());
            }
            receiverService.sendBatchMsg(team_im_id, to, connet);
        } else if (("sms").equals(pushType)) {
            try {
                StringBuilder phones = new StringBuilder();
                for (Ghost ghost : ghosts) {
                    User user = userRepository.selectByGid(ghost.getId());
                    phones.append(user.getPhone()).append(",");
                }
                pushService.sendSms(phones.toString(), "", connet);
            } catch (Exception e) {
                e.printStackTrace();
            }

        } else if (("sys").equals(pushType)) {
            List<String> ids = new ArrayList<>();
            for (Ghost ghost : ghosts) {
                ids.add(ghost.getId());
            }
            Result result = XiaomiPush.sendMessageToAliases(ids, "乐无通知", "乐无通知", connet);
            log.info("Server response: ", "MessageId: " + result.getMessageId()
                    + " ErrorCode: " + result.getErrorCode().getName()
                    + " Reason: " + result.getReason());

        }

    }

    private void setTotalCount(GroupType groupType, Map ghostCountByCreateDate) {
        if (ghostCountByCreateDate != null) {
            Object totalCount = ghostCountByCreateDate.get("totalCount");
            int count = Integer.valueOf(totalCount.toString());
            groupType.setUserTotal(count);
        } else {
            groupType.setUserTotal(0);
        }
    }
}
